﻿MPT.addAction("guide_info", function(_elm) {

    var male_jQ = $('.e_male', _elm);
    var year_jQ = $('.e_year', _elm);
    var month_jQ = $('.e_month', _elm);
    var day_jQ = $('.e_day', _elm);
    var province_jQ = $('.e_province', _elm);
    var city_jQ = $('.e_city', _elm);
    var submit_jQ = $('.e_submit', _elm);
    var skip_jQ = $('.e_skip', _elm);

    var no_friend_jQ = $('.e_no_friend', _elm);
    var add_friend_jQ = $('.e_add_friend', _elm);
    var friend_jQ = $('.e_friend', _elm);
    var add_jQ = $('.e_add', _elm);
    var add_all_jQ = $('.e_add_all', _elm);
    var residence_jQ = $('.e_residence', _elm);

    var m_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    var friend_list = [], adding = [];


    //初始化年份
    var html = [];
    for (var i = 1960; i <= 2012; i++) {
        html.push('<option value="' + i + '">' + i + '</option>');
    }
    year_jQ.append(html.join(''));

    //选择年份，填充月份，清空日期
    year_jQ.change(function() {

        html = [];
        for (var i = 1; i <= 12; i++) {
            html.push('<option value="' + i + '">' + i + '</option>');
        }
        month_jQ.html(html.join('')).prepend('<option value="0">月</option>').val(0);
        $("option[value='0']", year_jQ).remove();
        day_jQ.html('').prepend('<option value="0">日</option>').val(0);

        //闰年二月份加一天
        m_days[1] = isPinYear(year_jQ.val()) ? 29 : 28;
    });

    //选择月份，填充日期
    month_jQ.change(function() {
        html = [];
        for (var i = 1; i <= m_days[month_jQ.val() - 1]; i++) {
            html.push('<option value="' + i + '">' + i + '</option>');
        }
        day_jQ.html(html.join('')).prepend('<option value="0">日</option>').val(0);
        $("option[value='0']", month_jQ).remove();
    });

    day_jQ.change(function() {
        $("option[value='0']", day_jQ).remove();
    });

    //判断是否闰平年
    var isPinYear = function(year) {
        return (0 == year % 4 && (year % 100 != 0 || year % 400 == 0));
    }

    jQuery.getScript(MPT.Config.sta_js_lib_http + '/province_city_map.js', function() {

        //初始化省份
        html = [];
        $.each(province_city_map['province'], function(_pid, _prov) {
            html.push('<option value="' + _pid + '">' + _prov + '</option>');
        });
        province_jQ.append(html.join(''));

        //选择省份
        province_jQ.change(function() {

            //初始化城市
            html = [];
            $.each(province_city_map['relation'][province_jQ.val()], function(_cid, _city) {
                html.push('<option value="' + _city + '">' + province_city_map['city'][_city]['name'] + '</option>');
            });
            city_jQ.html(html.join('')).prepend('<option value="0">选择城市</option>').val(0);
            $("option[value='0']", province_jQ).remove();

            //初始化好友
            no_friend_jQ.hide();
            add_friend_jQ.show();
            residence_jQ.html(province_city_map['province'][province_jQ.val()]);

            $.ajax({
                type: "GET",
                url: MPT.Config["interface"]["findByProvice"],
                data: { "provinceId": province_jQ.val(), "pageSize": 8, "pageNo": 1 },
                success: function(_resp) {
                
                    Debug.info(_resp);

                    if (_resp == null || _resp == '') {
                        return;
                    }

                    var result = _resp["results"];
                    var html = [];
                    adding = [];

                    $.each(result, function(_i, _r) {

                        //添加一个状态记录是否被添加
                        var result = $.parseJSON(_r);
                        var nickname = Util.truncName(result.roleName, 6);
                        var userID = result.userId;
                        var avatarPath = Util.avatarPath(userID, 33);
                        result.isAdd = 0;
                        friend_list[_i] = result;

                        html.push('<li title="' + nickname + '">');
                        html.push('<div class="head"><span class="hide"></span><img src="' + avatarPath + '" alt="' + nickname + '"></div>');
                        html.push('<p class="name">' + nickname + '</p>');
                        html.push('</li>');
                    });

                    friend_jQ.html(html.join(''));

                    friend_jQ.find('li').toggle(function() {
                        $(this).find('div').addClass('active');
                    }, function() {
                        $(this).find('div').removeClass('active');
                    });
                },
                error: function() {
                    alert(1);

                }
            });
        });

        city_jQ.change(function() {
            $("option[value='0']", city_jQ).remove();
        });
    });

    submit_jQ.click(function() {

        var select_jQs = $('select', _elm);
        var validate = true;

        $.each(select_jQs, function(_i, _s) {

            if (_s.value == 0) {
                validate = false;
            }
        });

        if (validate) {
            jQuery.ajax({
                type: "POST",
                url: MPT.Config["interface"]["modifyUserInfo"],
                data: { "sex": male_jQ.is(':checked') ? 1 : 0,
                    "birthday": year_jQ.val() + fillDate(month_jQ.val()) + fillDate(day_jQ.val()),
                    "liveCityId": city_jQ.val()
                },
                dataType: 'json',
                success: function(_resp) {
                    window.location.hash = MPT.Config["hash"]["guide_avatar"];
                }
            });
        }
    });

    var fillDate = function(_num) {
        return _num.length == 1 ? '0' + _num : _num;
    }

    skip_jQ.click(function() {

        window.location.href = MPT.Config["hash"]["guide_avatar"];
    });

    add_jQ.click(function() {
        var batch_friend = [];

        $.each(friend_list, function(_i, _r) {

            var head_jQ = friend_jQ.find('div').eq(_i);
            var selected = head_jQ.is('div[class*=active]');

            if (_r.isAdd == 0 && selected) {
                batch_friend.push("{\"nickname\":\"" + _r.nickname + "\",\"uid\":\"" + _r.uid + "\"}");
                head_jQ.addClass('active').find('span').removeClass('hide').addClass('true');
                adding.push(_i);
            }
        });

        if (batch_friend.length > 0) {
            batchAddFriend("[" + batch_friend.join(',') + "]", adding);
        }
    });

    add_all_jQ.click(function() {
        var batch_friend = [];
        $.each(friend_list, function(_i, _r) {
            if (_r.isAdd == 0) {
                batch_friend.push("{\"nickname\":\"" + _r.nickname + "\",\"uid\":\"" + _r.uid + "\"}");
                adding.push(_i);
            }
        });

        friend_jQ.find("div").addClass('active').find('span').removeClass('hide').addClass('true');

        if (batch_friend.length > 0) {
            batchAddFriend("[" + batch_friend.join(',') + "]", adding);
        }

        friend_jQ.find('li').toggle(function() {
            $(this).find('div').removeClass('active');
        }, function() {
            $(this).find('div').addClass('active');
        });
    });

    var batchAddFriend = function(_batch, _adding) {

        jQuery.ajax({
            type: "POST",
            url: MPT.Config["interface"]["batchSendMessage"],
            data: { "targetUser": _batch },
            dataType: 'json',
            success: function(_resp) {
                if (_resp == 1) {
                    $.each(_adding, function(_i, _id) {
                        friend_list[_id]["isAdd"] = 1;
                    });
                }
            }
        });
    };
});

